const {error} = require('../utils/message');
const getPermissions = require('../utils/get-permissions')

// 权限认证
module.exports = function (options) {
    return async function (req, res, next) {
        // 如果是超级管理员
        if (req.decoded.user.id === 1) {
            return next()
        }

        // 当前用户组的权限数组
        const permissions = await getPermissions(req.decoded.user.roleId)

        // 用户请求的方式和接口地址
        const path = req.route.path !== '/' ? req.route.path : ''
        const request = `${req.method} ${req.baseUrl}${path}`
        console.log(request)
        // 判断是否存在权限
        if (permissions.indexOf(request) === -1) {
            return error(res, '你没有权限进行此操作！', 50001)
        }

        next()
    }
}
